<template>
  <div class="record-detail-container">
    <el-page-header @back="goBack">
      <template #content>
        <span class="page-title">会话详情</span>
      </template>
    </el-page-header>

    <div class="detail-content" v-loading="loading">
      <template v-if="record">
        <div class="detail-layout">
          <!-- 左侧：基本信息卡片 -->
          <el-card class="info-card">


            <div class="user-profile">
              <el-avatar :size="64" :src="record.user?.avatar">
                <el-icon><User /></el-icon>
              </el-avatar>
              <div class="user-profile-info">
                <h3>{{ record.user?.username }}</h3>
                <p class="user-id">ID: {{ record.user_id || record.user?.id || '-' }}</p>
              </div>
            </div>

            <el-divider />

            <el-descriptions :column="1" border>
              <el-descriptions-item label="记录ID">
                <el-tag effect="plain">{{ record.id }}</el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="查询时间">
                {{ formatTimestamp(record.timestamp) }}
              </el-descriptions-item>
              <el-descriptions-item label="会话名称">
                <el-tag size="small" effect="dark">{{ record.session.session_title}}</el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="模型">
                <el-tag
                  size="small"
                  effect="dark"
                  :type="getModelTagType(record.model_type)"
                >
                  {{ record.model_type || '未知模型' }}
                </el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="Token消耗">
                <div class="tokens-info">
                  <el-tooltip content="查询消耗的Token数" placement="top">
                    <el-tag type="info" effect="plain" size="small">
                      <el-icon><ChatLineSquare /></el-icon> {{ formatTokens(record.query_tokens) }}
                    </el-tag>
                  </el-tooltip>
                  <el-tooltip content="回答消耗的Token数" placement="top">
                    <el-tag type="info" effect="plain" size="small">
                      <el-icon><ChatDotRound /></el-icon> {{ formatTokens(record.response_tokens) }}
                    </el-tag>
                  </el-tooltip>
                  <el-tooltip content="总Token消耗" placement="top">
                    <el-tag
                      :type="getTokenColorType(record.total_tokens)"
                      size="small"
                    >
                      <el-icon><ChatDotSquare /></el-icon> {{ formatTokens(record.total_tokens) }}
                    </el-tag>
                  </el-tooltip>
                </div>
              </el-descriptions-item>
              <el-descriptions-item label="管理员备注">
                <div class="note-content">
                  {{ record.admin_notes || '暂无备注' }}
                </div>
              </el-descriptions-item>
            </el-descriptions>
          </el-card>

          <!-- 右侧：对话内容卡片 -->
          <el-card class="qa-card">
            <template #header>
              <div class="card-header">
                <span>
                  <el-icon><ChatLineRound /></el-icon>
                  对话内容
                  <el-tag v-if="record.system_replies && record.system_replies.length > 1"
                         type="info" class="message-count" size="small">
                    {{ record.system_replies?.length || 0 }} 条消息
                  </el-tag>
                </span>
              </div>
            </template>

            <div class="chat-content">
              <!-- 用户查询 -->
              <div class="message user-message">
                <div class="message-avatar">
                  <el-avatar :size="40" :src="record.user_avatar || record.user?.avatar">
                    <el-icon><User /></el-icon>
                  </el-avatar>
                </div>
                <div class="message-content">
                  <div class="message-header">
                    <span class="message-name">{{ record.user_name || record.user?.username || '用户' }}</span>
                    <span class="message-time">{{ formatTimestamp(record.query_time || record.timestamp) }}</span>
                  </div>
                  <div class="message-body user-bubble">
                    <p>{{ record.query_content || record.message }}</p>
                  </div>

                  <!-- 用户意图和确认信息 -->
                  <div v-if="record.message_confirm" class="message-metadata">
                    <div v-if="record.message_confirm" class="metadata-box">
                      <div class="metadata-header">
                        <el-icon><Select /></el-icon> 确认信息
                      </div>
                      <div class="metadata-content">{{ record.message_confirm }}</div>
                    </div>
                  </div>

                  <!-- SQL语句 -->
                  <div v-if="record.message_sql" class="message-metadata">
                    <div class="metadata-box">
                      <div class="metadata-header">
                        <el-icon><DataAnalysis /></el-icon> SQL语句
                        <el-button type="primary" text size="small" @click="copySql(record.message_sql)">
                          <el-icon><CopyDocument /></el-icon> 复制
                        </el-button>
                      </div>
                      <pre class="sql-content">{{ record.message_sql }}</pre>
                    </div>
                  </div>
                </div>
              </div>

              <!-- 系统回复 -->
              <div v-for="(reply, index) in record.system_replies || [record.response]"
                   :key="index"
                   class="message system-message">
                <div class="message-avatar">
                  <el-avatar :size="40" class="system-avatar">
                    <el-icon><ChatDotRound /></el-icon>
                  </el-avatar>
                </div>
                <div class="message-content">
                  <div class="message-header">
                    <span class="message-name">{{ reply.message_model || record.model_type || '系统' }}</span>
                    <span class="message-time">{{ formatTimestamp(reply.timestamp || record.response_time) }}</span>
                  </div>
                  <div class="message-body system-bubble">
                    <p>{{ reply.message || record.response_content }}</p>
                  </div>

                  <!-- 回复SQL语句 -->
                  <div v-if="reply.message_sql" class="message-metadata">
                    <div class="metadata-box">
                      <div class="metadata-header">
                        <el-icon><DataAnalysis /></el-icon> SQL语句
                        <el-button type="primary" text size="small" @click="copySql(reply.message_sql)">
                          <el-icon><CopyDocument /></el-icon> 复制
                        </el-button>
                      </div>
                      <pre class="sql-content">{{ reply.message_sql }}</pre>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </el-card>
        </div>
      </template>

      <!-- 数据不存在提示 -->
      <el-empty
        v-else-if="!loading"
        description="会话不存在或已被删除"
      >
        <el-button type="primary" @click="goBack">返回列表</el-button>
      </el-empty>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { useQueryRecordStore } from '@/stores/queryRecord'
import {
  formatTimestamp,
  formatTokens,
  getTokenColorType,
} from '@/utils/queryDataProcessor'
import {
  User,
  CopyDocument,
  ChatDotRound,
  ChatLineRound,
  ChatLineSquare,
  ChatDotSquare,
  Aim,
  Select,
  DataAnalysis
} from '@element-plus/icons-vue'

// 定义组件名称
defineOptions({
  name: 'SessionDetail'
})

// 路由
const route = useRoute()
const router = useRouter()
const recordId = computed(() => route.params.id)

// Store
const recordStore = useQueryRecordStore()

// 组件状态
const loading = ref(false)
const record = ref(null)

// 方法：导航
const goBack = () => {
  router.push({ name: 'RecordsList' })
}

// 方法：加载记录
const fetchRecordDetail = async () => {
  if (!recordId.value) return

  loading.value = true
  try {
    // 首先检查当前store中的records数组，看是否已包含此记录数据
    const existingRecord = recordStore.records.find(r => r.id === recordId.value)

    if (existingRecord) {
      // 如果在store中找到数据，直接使用，无需再次请求API
      record.value = existingRecord
      return
    }

    // 如果store中没有数据，则使用简化的params请求特定消息
    const params = {
      session_id: recordId.value
    }
    const result = await recordStore.getAdminMessages(params)

    if (result.data && result.data.length > 0) {
      record.value = result.data[0]
      return
    }

    // 如果通过session_id没找到，尝试直接获取记录
    await recordStore.fetchRecordById(recordId.value)
    record.value = recordStore.currentRecord
  } catch (error) {
    console.error('获取记录详情失败', error)
    ElMessage.error('获取记录详情失败')
  } finally {
    loading.value = false
  }
}

// 复制SQL语句方法
const copySql = (sql) => {
  navigator.clipboard.writeText(sql).then(() => {
    ElMessage.success('SQL已复制到剪贴板')
  }).catch(() => {
    ElMessage.error('复制失败')
  })
}

// 辅助函数
const getModelTagType = (modelType) => {
  if (!modelType) return ''

  if (modelType.includes('gpt-3')) return 'success'
  if (modelType.includes('gpt-4')) return 'primary'
  if (modelType.includes('claude')) return 'warning'

  return 'info'
}

// 监听路由参数变化，解决重复点击同一组件时onMounted不触发的问题
watch(() => route.params.id, (newId) => {
  if (newId) {
    fetchRecordDetail()
  }
}, { immediate: true })

// 页面加载
onMounted(() => {
  fetchRecordDetail()
})
</script>

<style scoped>
.record-detail-container {
  padding: 20px;
  height: auto;
  min-height: calc(100vh - 100px);
  overflow: visible;
}

.page-title {
  font-size: 18px;
  font-weight: bold;
}

.detail-content {
  margin-top: 20px;
  height: auto;
  overflow: visible;
}

.detail-layout {
  display: grid;
  grid-template-columns: 450px 1fr;
  gap: 20px;
  min-height: calc(100vh - 200px);
  overflow: visible;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header span {
  display: flex;
  align-items: center;
  gap: 5px;
}

.info-card {
  height: fit-content;
  position: sticky;
  top: 20px;
}

.qa-card {
  height: auto;
  overflow: visible;
  display: flex;
  flex-direction: column;
}

:deep(.el-card__body) {
  overflow: visible;
}

.user-profile {
  display: flex;
  align-items: center;
  gap: 15px;
  margin-bottom: 20px;
}

.user-profile-info {
  display: flex;
  flex-direction: column;
}

.user-profile-info h3 {
  margin: 0 0 5px 0;
}

.user-id {
  margin: 0;
  color: #909399;
  font-size: 13px;
}

.tokens-info {
  display: flex;
  gap: 8px;
}

.chat-content {
  display: flex;
  flex-direction: column;
  gap: 24px;
  margin-bottom: 20px;
}

.message {
  display: flex;
  gap: 12px;
}

.message-avatar {
  flex-shrink: 0;
}

.message-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.message-header {
  display: flex;
  align-items: center;
  gap: 8px;
}

.message-name {
  font-weight: 500;
  font-size: 14px;
}

.message-time {
  font-size: 12px;
  color: #909399;
}

.message-body {
  padding: 12px 16px;
  border-radius: 12px;
  max-width: 100%;
}

.message-body p {
  margin: 0;
  white-space: pre-wrap;
  line-height: 1.6;
}

.user-bubble {
  border-radius: 4px 16px 16px 16px;
}

.system-bubble {
  border-radius: 16px 4px 16px 16px;
}

.system-avatar {
  background-color: #409EFF;
  color: white;
}

.message-metadata {
  margin-top: 8px;
  width: 100%;
}

.metadata-box {
  border-radius: 8px;
  margin-bottom: 8px;
  overflow: hidden;
}

.metadata-header {
  padding: 10px 12px;
  font-size: 14px;
  font-weight: 500;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.metadata-content {
  padding: 12px;
  white-space: pre-wrap;
  line-height: 1.5;
}

.sql-content {
  border-radius: 0;
  padding: 12px;
  overflow-x: auto;
  font-family: 'Fira Code', 'Courier New', monospace;
  font-size: 13px;
  max-height: 200px;
  overflow-y: auto;
  white-space: pre-wrap;
  margin: 0;
}

.message-count {
  margin-left: 8px;
}

.note-content {
  white-space: pre-line;
  color: var(--el-text-color-regular);
}

@media (max-width: 992px) {
  .detail-layout {
    grid-template-columns: 1fr;
  }
}
</style>
